<template>
  <div class="app-container calendar-list-container">
    <!-- filter 条件查询 -->
    <div class="filter-container">
      <el-input 
        clearable 
        @keyup.enter.native="handleFilter" 
        v-model="listQuery.nickName" 
        style="width: 200px;margin-right:15px;" 
        class="filter-item" 
        :placeholder="$t('placeholder.nickName')" >
      </el-input>
      <el-input 
      clearable 
      @keyup.enter.native="handleFilter" v-model="listQuery.usersPhone" style="width: 200px;margin-right:15px;" class="filter-item" 
      :placeholder="$t('placeholder.userPhone')" >
      </el-input>
      <el-select v-model="listQuery.isFlag" :placeholder="$t('placeholder.status')" clearable class="filter-item" style="width: 250px;">
        <el-option :label="$t('table.Enabled')" value="1"></el-option>
        <el-option :label="$t('table.Disabled')" value="2"></el-option>
      </el-select>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">{{$t('common.Search')}}</el-button>
      <el-button  type='primary' v-waves  class="filter-item" @click="handleDownload"  icon="el-icon-download"  :loading="downloadLoading">{{$t('common.Export')}}</el-button>
    </div>
    <!-- table 表格 -->
    <el-table  :data="list" v-loading="loading.list" :element-loading-text="$t('common.Loading')" border fit highlight-current-row
      style="width: 100%">
      <el-table-column  :label="$t('table.sort')" prop='userId'/>
      <el-table-column  :label="$t('table.User_name')" prop='nickName' />
      <el-table-column  :label="$t('table.Phone_number')" prop='usersPhone' />
      <el-table-column  :label="$t('table.Link_to_Facebook')" prop='facebook' />
      <el-table-column  :label="$t('table.Link_to_Wechat')" prop='smallProgramOpenId' />
      <el-table-column  :label="$t('table.Balance')" prop='balance' />
      <el-table-column  :label="$t('table.Deposit')" prop='deposit' />
      <el-table-column  :label="$t('table.Point')" prop='integral' />
      <el-table-column  :label="$t('table.Invitation_code')" prop='invitation' />
      <el-table-column  :label="$t('table.User_status')" prop='isFlag'>
        <template slot-scope="scope">
          {{scope.row.isFlag == 1? $t('user.Normal_user') : $t('user.Disabled_user')}}
        </template>
      </el-table-column>
      <el-table-column  :label="$t('table.Profile_icon')" width="100">
        <template slot-scope="scope">
           <img :src="scope.row.usersPic" alt="" style="width:80px;height:80px">
        </template>
      </el-table-column>
      <el-table-column  :label="$t('table.Created_time')">
         <template slot-scope="scope">
           {{scope.row.ctime | parseTime}}
        </template>
       </el-table-column>
      <el-table-column  :label="$t('table.Operate')"  class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <div class="fy">
            <!-- <el-button  type='text' >详情</el-button> -->
            <el-button  type='text' @click="getEditData(scope.row)">{{$t('table.Edit')}}</el-button>
            <el-button  v-if="scope.row.isFlag == 2" @click="changeStatus(scope.row.userId,1)" type='primary'>{{$t('table.Enabled')}}</el-button>
            <el-button size="small" v-else type="danger" @click="changeStatus(scope.row.userId,2)">{{$t('table.Disabled')}}</el-button>          
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination 
      background 
      @size-change="handleSizeChange" 
      @current-change="handleCurrentChange" 
      :current-page="listQuery.pageNo" 
      :page-sizes="[10, 20, 30, 40]" 
      :page-size="listQuery.pageSize" 
      layout="total, sizes, prev, pager, next, jumper" 
      :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="$t('user.Edit_user_infomation')" :visible.sync="dialog.add">
      <el-form :model="editQuery"  ref="bindForm"  label-position="right" label-width="120px"> 
        <el-form-item :label="$t('table.User_name')" prop="nickName">
         <el-input  clearable v-model="editQuery.nickName" :placeholder="$t('table.User_name')"></el-input>
        </el-form-item>
        <el-form-item :label="$t('common.Gender')" prop="gender">
          <el-radio-group v-model="editQuery.gender">
            <el-radio :label='1'>{{$t('common.Male')}}</el-radio>
            <el-radio :label="2">{{$t('common.Female')}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('common.Email')" prop="email">
         <el-input  clearable v-model="editQuery.email" :placeholder="$t('common.Email')"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.add = false">{{$t('common.Cancel')}}</el-button>
        <el-button type="primary" :loading="loading.add" @click="add">{{$t('common.Confirm')}}</el-button>
      </div>
    </el-dialog>
    <!-- 回到顶部 -->
    <BackToTop></BackToTop>
  </div>
</template>

<script>
import { getList,getUser,getStatus,setUserIsFlag,updateUserById} from '@/api/user'
import { validatePhone } from '@/utils/validate'
import { parseTime } from '@/utils'
import BackToTop from '@/components/BackToTop'
export default {
  components: {
    BackToTop
  },
  name: 'user_list',
  data() {
    var validatePass = (rule, value, callback) => {
      if (!validatePhone(value)) {
        return callback(new Error('请填写正确的手机号码'));
      } else {
        callback();
      }
    };
    return {
    total: 0,
    listQuery: {
      pageNo: 1,
      pageSize: 10,
      nickName: '',
      usersPhone:''
    },
    list: null,
    loading: {
      list: false,
      add: false
    },
    dialog:{
      add:false
    },
    editQuery:{
      userId: '',
      nickName: '',
      gender: '',
      email: ''
    },
    roleList:[
      {userType:2,name:'维修'},
      {userType:3,name:'保洁'}
    ],
    downloadLoading: false,
      
    }
  },
  methods: {
    //导出
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['用户昵称', '手机号', '用户性别','关联微信Facebook', '余额', '押金金额','积分','邀请码','用户状态','创建时间']
        const filterVal = ['nickName', 'usersPhone', 'genderLabel','facebook', 'balance', 'deposit','integral','invitation', 'isFlagLabel', 'ctime']
        const data = this.formatJson(filterVal, this.list)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: this.$t('route.User_list')
        })
        this.downloadLoading = false
      })
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
      if (j === 'ctime') {
        return parseTime(v[j])
      } else {
        return v[j]
      }
      }))
    },
    //获取用户列表
    async getList() {
      this.loading.list = true
      try {
        const { data } = await getList(this.listQuery)
        this.list = data.records.map((item, index) => ({
          index: index + 1, 
          ...item,
          isFlagLabel: item.isFlag == 1 ? '正常用户' : '禁用用户',
          genderLabel: item.gender == 1 ? '男' : '女',
          loginCtime: parseTime(item.loginCtime)
        }))
        this.total = data.total
      } catch (error) {
        
      }
      this.loading.list = false     
    },
    //禁用启用
    changeStatus(userId,isFlag) {
          let type = isFlag == 1 ? this.$t('table.Enabled'): this.$t('table.Disabled')
          this.$confirm(`${this.$t('common.Whether')} ${type}?`, this.$t('common.Tip'), {
            confirmButtonText: this.$t('common.Confirm'),
            cancelButtonText: this.$t('common.Cancel'),
            type: 'warning'
          }).then(async () => {
              const {data }= await setUserIsFlag({
                userId,
                isFlag
              })
              this.$message({
                  type: 'success',
                  message: this.$t('common.Successful_operation')
              });
                this.getList()
              }).catch(() => {
                    
              });
      }, 
    //查找
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNo = val
      this.getList()
    },
    //编辑
    getEditData ({userId,nickName,gender,email}) {
      this.dialog.add = true
      this.editQuery = Object.assign({}, this.editQuery, {userId, nickName, gender, email})
    },
    async add() {
      this.loading.add = true
      try{
        const res = await updateUserById(this.editQuery)
        this.$message({
          type:'success',
          message: this.$t('common.Successful_operation')
        })
        this.getList()
        this.dialog.add = false
      } catch(error) {
        this.loading.add = false
      }
      this.loading.add = false
    }
  },
  created() {
    this.getList()
  },
}
</script>
